package com.yzq.authorization.server.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yzq.authorization.server.constants.RedisConstants;
import com.yzq.authorization.server.model.CaptchaResult;
import com.yzq.authorization.server.model.Result;
import com.yzq.authorization.server.support.RedisOperator;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: yangjie.deng@resico.cn
 * @since: 2024-01-30 16:19:17
 * @version: v1.0.0
 * @describe:
 */
@RestController
@RequiredArgsConstructor
public class CaptchaController {

    private final RedisOperator<String> redisOperator;

    @GetMapping("captcha")
    public Result<CaptchaResult> getCaptcha() {
        // 使用huTool-captcha生成图形验证码
        // 定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(150, 40, 4, 2);
        // 生成一个唯一id
        long id = IdWorker.getId();
        // 存入缓存中，5分钟后过期
        redisOperator.set((RedisConstants.IMAGE_CAPTCHA_PREFIX_KEY + id), captcha.getCode(), RedisConstants.DEFAULT_TIMEOUT_SECONDS);

        return Result.success("获取验证码成功.", new CaptchaResult(String.valueOf(id), captcha.getCode(), captcha.getImageBase64Data()));
    }
}
